package com.ligongmusic.activity;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.ligongmusic.R;
import com.ligongmusic.domain.Upload;
import com.ligongmusic.util.DialogUtils;
import com.ligongmusic.util.GlobalParams;
import com.ligongmusic.util.JsonUtils;
import com.ligongmusic.util.NetWorkUtils;
import com.ligongmusic.util.StringUtils;
import com.ligongmusic.view.TopManager;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2016/8/30.
 */
public class SupplementMusic extends Activity {
    private Uri uritempFile;
    private Bitmap bitmap;
    private File lrcFile;
    private TextView tv_lrc_name;
    private Upload music;
    private ImageView musicIcon;
    private EditText et_composer;
    private EditText et_producer;
    private TextView singer_status;
    private TextView tv_original;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.music_upload);
        music = (Upload) getIntent().getSerializableExtra("music");
        initView();
    }

    private void initView() {
        musicIcon = (ImageView) findViewById(R.id.music_icon);
        et_composer = (EditText) findViewById(R.id.et_composer);
        et_producer = (EditText) findViewById(R.id.et_producer);
//        singer_status = (TextView) findViewById(R.id.singer_status);
        tv_original = (TextView) findViewById(R.id.tv_original);
        et_composer.setText(StringUtils.isEmpty(music.getComposer()) ? "" : music.getComposer());
        et_producer.setText(StringUtils.isEmpty(music.getLyricist()) ? "" : music.getLyricist());
        tv_original.setText(music.getIsoriginalsong() == 0 ? "翻唱" : "原唱");
//        singer_status.setText();
        ((RelativeLayout)findViewById(R.id.rl_original)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtils.selectDialog(SupplementMusic.this, new String[]{"翻唱", "原唱"}, new DialogUtils.SelectCallBack() {
                    @Override
                    public void select(String item) {
                        tv_original.setText(item);
                    }
                });
            }
        });
        ((RelativeLayout)findViewById(R.id.rl_select_lrc)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/.lrc");//设置类型，我这里是任意类型，任意后缀的可以这样写。
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(intent,0x1);
            }
        });
        new Thread() {
            @Override
            public void run() {
                super.run();
                Bitmap bit = ImageLoader.getInstance().loadImageSync(GlobalParams.IMAGE_URL + music.getCover());
                if (bitmap == null) {
                    bitmap = bit;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            musicIcon.setImageBitmap(bitmap);
                        }
                    });
                }
            }
        }.start();
        TopManager.getTopManager(this).showTop(true, "歌曲信息", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tv_lrc_name = (TextView) findViewById(R.id.tv_lrc_name);
        tv_lrc_name.setText(StringUtils.isEmpty(music.getLyric()) ? "" : music.getLyric());
        ((RelativeLayout) findViewById(R.id.rl_music_icon)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtils.selectDialog(SupplementMusic.this, new String[]{"相册", "拍照"}, new DialogUtils.SelectCallBack() {
                    @Override
                    public void select(String item) {
                        if (item.contains("相册")) {
                            Intent intent = new Intent();
                            /* 开启Pictures画面Type设定为image */
                            intent.setType("image/*");
                            intent.setAction(Intent.ACTION_GET_CONTENT);
                            //						intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
							/* 取得相片后返回本画面 */
                            startActivityForResult(intent, 0x2);
                        } else {
                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            startActivityForResult(intent, 0x2);
                        }
                    }
                });
            }
        });

        ((Button)findViewById(R.id.bt_submit)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String original = tv_original.getText().toString().trim();
                if (StringUtils.isEmpty(original)){
                    Toast.makeText(getApplicationContext(), "请选择是否原唱", Toast.LENGTH_SHORT).show();
                    return;
                }
                String isOriginal = "原唱".equals(original) ? "1" : "0";
                String composer = et_composer.getText().toString().trim();
                String producer = et_producer.getText().toString().trim();
                try {
                    upload(isOriginal, composer, producer);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void upload(String isOriginal, String composer, String producer) throws IOException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("cover", bitmap == null ? "" : bitmap);
        map.put("composer", composer);
        map.put("id", music.getId() + "");
        map.put("lyricist", producer);
        map.put("isoriginalsong", isOriginal);
        map.put("lyric", lrcFile == null ? "" : lrcFile);
        NetWorkUtils.uploadInfo("", GlobalParams.INSERT_MUSIC_INFO, map, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Toast.makeText(getApplicationContext(), JsonUtils.getString(responseInfo.result, "message"), Toast.LENGTH_SHORT).show();
                if ("200".equals(JsonUtils.getString(responseInfo.result, "code"))){
                    setResult(0x2);
                    finish();
                }
            }


            @Override
            public void onFailure(HttpException error, String msg) {

            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null) {//用户取消
            return;
        }
        if (requestCode == 0x1) {
//			LoggerUtils.getLog(UploadMusic.class).error(data.getData().toString());
            if (data == null)// 用户取消
                return;
//			String dataString = Uri.decode(data.getDataString());
            String decode = Uri.decode(data.getData().getPath());
            if (decode == null)
                return;
            try {
                String[] split = decode.split(":");
                String filePath = split[split.length - 1];
                if (filePath == null)
                    return;
                lrcFile = new File(data.getData().toString());
                tv_lrc_name.setText(filePath);
            } catch (Exception e) {
                lrcFile = new File(data.getData().toString());
                tv_lrc_name.setText(lrcFile.getName());
            }
        } else if (requestCode == 0x2) {

            // 图片
            Uri uri = getUri(data);
            if (uri == null)
                return;
            crop(uri);
        } else if (requestCode == 0x3) {
            try {
                bitmap = BitmapFactory.decodeStream(SupplementMusic.this.getContentResolver().openInputStream(uritempFile));
                musicIcon.setImageBitmap(bitmap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /*
    * 剪切图片
    */
    private void crop(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");

        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", 250);
        intent.putExtra("outputY", 250);

        /**
         * 此方法返回的图片只能是小图片（sumsang测试为高宽160px的图片）
         * 故将图片保存在Uri中，调用时将Uri转换为Bitmap，此方法还可解决miui系统不能return data的问题
         */
        //intent.putExtra("return-data", true);

        uritempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "xx.jpg");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

        startActivityForResult(intent, 0x3);
    }

    /**
     * 解决小米手机上获取图片路径为null的情况
     *
     * @param intent
     * @return
     */
    public Uri getUri(android.content.Intent intent) {
        Uri uri = intent.getData();
        String type = intent.getType();
        if (uri.getScheme().equals("file") && (type.contains("image/"))) {
            String path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = SupplementMusic.this.getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=")
                        .append("'" + path + "'").append(")");
                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        new String[]{MediaStore.Images.ImageColumns._ID},
                        buff.toString(), null, null);
                int index = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                    // set _id value
                    index = cur.getInt(index);
                }
                if (index == 0) {
                    // do nothing
                } else {
                    Uri uri_temp = Uri
                            .parse("content://media/external/images/media/"
                                    + index);
                    if (uri_temp != null) {
                        uri = uri_temp;
                    }
                }
            }
        }
        return uri;
    }
}
